﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Collections;
using System.Configuration;
using System.Web.Configuration;

namespace SPWP.OpinionPoll
{
    public class PollVoteListAnswer
    {
        private string listLocation = WebConfigurationManager.AppSettings["listpoll"].ToString();

        public string SPPollSite { get; set; }
        public string SPPollList { get; set; }
        public string SPPollListAnswer { get; set; }
        public string SPPollListVote { get; set; }

        string spsite;

        public PollVoteListAnswer(string splist, string splistanswer)
        {
            spsite = SPPollSite;
            SPPollList = splist;
            SPPollListAnswer = splistanswer;
        }

        public PollVoteListAnswer(string spvotelist)
        {
            SPPollListVote = spvotelist;
        }

        public PollVoteListAnswer()
        {
            
        }

        /// <summary>
        /// Add new poll answer
        /// </summary>
        /// <param name="itemAdd">New poll answer list details</param>
        /// <returns>Status flag</returns>
        public bool AddPollAnswer(List<PollVote> itemAddList)
        {
            try
            {
                bool isCreated = false;
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite objSite = new SPSite(listLocation))
                    {
                        using (SPWeb objWeb = objSite.OpenWeb())
                        {
                            bool unSafeUpdate = objWeb.AllowUnsafeUpdates;
                            objWeb.AllowUnsafeUpdates = true;

                            SPList objList = objWeb.Lists[SPPollListVote];

                            foreach (PollVote item in itemAddList)
                            { 
                                SPListItem objItem = objList.Items.Add();
                                objItem["Title"] = SPPollListVote;
                                objItem["VoterEmail"] = item.IPAddress;
                                objItem["AnswerPicked"] = item.AnswerPicked;

                                objItem.Update();
                            }

                            isCreated = true;

                            objWeb.AllowUnsafeUpdates = unSafeUpdate;


                        }
                    }
                });

                return isCreated;

            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// Query one poll details
        /// </summary>
        /// <returns>One poll details</returns>
        public PollMasterAnswer GetActivePoll()
        {
            PollMasterAnswer foundPoll = new PollMasterAnswer();

            try
            {
                using (SPSite objSite = new SPSite(listLocation))
                {
                    using (SPWeb objWeb = objSite.OpenWeb())
                    {
                        // retrieve survey question
                        SPQuery query = new SPQuery();
                        query.ViewFields = @"<FieldRef Name=""Title"" /><FieldRef Name=""Active"" /><FieldRef Name=""AnonsCanVote"" /><FieldRef Name=""Category"" /><FieldRef Name=""ExpiresOn"" /><FieldRef Name=""ID"" /><FieldRef Name=""SortOrder"" /><FieldRef Name=""MultipleChoice"" /><FieldRef Name=""Author"" /><FieldRef Name=""Created"" /><FieldRef Name=""Editor"" /><FieldRef Name=""Modified"" />";
                        query.Query = @"<Query><OrderBy><FieldRef Name=""ExpiresOn""></FieldRef></OrderBy><Where><And><Eq><FieldRef Name=""Active""></FieldRef><Value Type=""Choice"">Yes</Value></Eq><Ge><FieldRef Name=""ExpiresOn""></FieldRef><Value Type=""DateTime""><Today /></Value></Ge></And></Where></Query>";
                        
                        //query.RowLimit = 1;

                        SPList objList = objWeb.Lists[SPPollList];
                        SPListItemCollection filteredItems = objList.GetItems(query);
                
                        foreach (SPListItem item in filteredItems)
                        {
                            if ((String.Compare(item["Active"].ToString(), "Yes", true)==0) && (DateTime.Compare(DateTime.Parse(item["ExpiresOn"].ToString()), DateTime.Now) > 0))
                            { 
                                foundPoll.PollID = Convert.ToInt32(item["ID"]);
                                foundPoll.PollTitle = item["Title"].ToString();
                                foundPoll.ExpireOn = DateTime.Parse(item["ExpiresOn"].ToString());
                                foundPoll.IsActive = item["Active"].ToString();
                                foundPoll.AnonymousVote = item["AnonsCanVote"].ToString();
                                foundPoll.MultiChoice = item["MultipleChoice"].ToString();

                                //char[] separator = { '#' };
                                //string category = item["Category"].ToString().TrimStart(separator);

                                //foundPoll.Category = category;
                            }
                        }

                        // retrieve survey answer
                        int pollID = foundPoll.PollID;
                        foundPoll.PollAnswerList = GetAnswer(pollID);
                    }
                }

            }
            catch (Exception ex)
            {
                 //String.Format("{0}: {1}", ErrorMessage.Error, ex.Message);
            }

            return foundPoll;

        }

        /// <summary>
        /// Get Poll Results
        /// </summary>
        /// <param name="pollID">Poll ID to be viewed</param>
        /// <returns>One poll details</returns>
        public List<PollVote> GetResult(int poll)
        {
            List<PollVote> listVote = new List<PollVote>();

            try
            {
                using (SPSite objSite = new SPSite(listLocation))
                {
                    using (SPWeb objWeb = objSite.OpenWeb())
                    {
                        // retrieve survey question
                        SPQuery query = new SPQuery();
                        query.ViewFields = @"<FieldRef Name=""AnswerPicked"" /><FieldRef Name=""Title"" /><FieldRef Name=""VoterEmail"" />";
                        query.Query = @"<Query><Where><IsNotNull><FieldRef Name=""Title"" /></IsNotNull></Where></Query>";

                        string title = "Poll Votes-" + poll.ToString();

                        SPList objList = objWeb.Lists[title];
                        SPListItemCollection filteredItems = objList.GetItems(query);
                
                        foreach (SPListItem item in filteredItems)
                        { 
                            PollVote voteItem = new PollVote();

                            voteItem.Title = item["Title"].ToString();
                            voteItem.AnswerPicked = item["AnswerPicked"].ToString();
                            voteItem.IPAddress = item["VoterEmail"].ToString();

                            listVote.Add(voteItem);
                        }
                    }
                }


            }
            catch (Exception ex)
            {
                 //String.Format("{0}: {1}", ErrorMessage.Error, ex.Message);
            }

            return listVote;

        }

        public List<PollAnswer> GetAnswer(int poll)
        {
            List<PollAnswer> answerList = new List<PollAnswer>();

            try
            {
                using (SPSite objSite = new SPSite(listLocation))
                {
                    using (SPWeb objWeb = objSite.OpenWeb())
                    {
                        SPQuery queryAnswer = new SPQuery();
                        queryAnswer.ViewFields = @"<FieldRef Name=""Title"" /><FieldRef Name=""DisplayOrder"" /><FieldRef Name=""ID"" /><FieldRef Name=""PollID"" />";
                        queryAnswer.Query = @"<Query><OrderBy><FieldRef Name=""DisplayOrder""></FieldRef></OrderBy><Where><Eq><FieldRef Name=""PollID"" /><Value Type=""Number"">" + poll + "</Value></Eq></Where></Query>";

                        SPList objListAnswer = objWeb.Lists[SPPollListAnswer];
                        SPListItemCollection filteredItemsAnswer = objListAnswer.GetItems(queryAnswer);

                        foreach (SPListItem item in filteredItemsAnswer)
                        {
                            if (poll.Equals(Convert.ToInt32(item["PollID"])))
                            {
                                PollAnswer foundAnswer = new PollAnswer();

                                foundAnswer.PollID = Convert.ToInt32(item["PollID"].ToString());
                                foundAnswer.ID = Convert.ToInt32(item["ID"].ToString());
                                foundAnswer.Answer = item["Title"].ToString().Trim();
                                foundAnswer.SortOrder = Convert.ToInt32(item["DisplayOrder"].ToString());

                                answerList.Add(foundAnswer);
                            }
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                //String.Format("{0}: {1}", ErrorMessage.Error, ex.Message);
            }

            return answerList;
        }

        public List<ResultVote> CalcResult(int poll)
        {
            List<PollVote> voteList = GetResult(poll);
            
            List<ResultVote> resultStat = new List<ResultVote>();

            // start list answer
            List<PollAnswer> answerList = GetAnswer(poll);
            // get list of answers
            var answers = from p in answerList
                          orderby p.SortOrder
                           select p.Answer;

            // start calculating
            var itemCount = from i in voteList
                            group i by i.AnswerPicked into g
                            select new { Answer = g.Key , TotalAnswer = g.Count() };

            var itemAvailable = from j in voteList
                                select j.AnswerPicked;

            foreach (var j in itemCount)
            {
                resultStat.Add(new ResultVote { Item = j.Answer, TotalCount = j.TotalAnswer });
            }

            // compare two result
            IEnumerable<string> differenceQuery = answers.Except(itemAvailable);
            foreach (string s in differenceQuery)
            {
                resultStat.Add(new ResultVote { Item = s, TotalCount = 0 });
            }

            //return resultStat;
            List<ResultVote> resultSorted = new List<ResultVote>();
            foreach (var k in answers)
            {
                var result = resultStat.Find(x => x.Item == k);
                resultSorted.Add(result);
            }
            return resultSorted;
        }

        /// <summary>
        /// Query one poll details
        /// </summary>
        /// <param name="pollID">Poll ID to be viewed</param>
        /// <returns>One poll details</returns>
        public PollMaster ViewPollByID(int pollID)
        {
            PollMaster foundPoll = new PollMaster();

            try
            {
                using (SPSite objSite = new SPSite(listLocation))
                {
                    using (SPWeb objWeb = objSite.OpenWeb())
                    {
                        SPQuery query = new SPQuery();
                        query.ViewFields = @"<FieldRef Name=""Title"" /><FieldRef Name=""Active"" /><FieldRef Name=""AnonsCanVote"" /><FieldRef Name=""Category"" /><FieldRef Name=""ExpiresOn"" /><FieldRef Name=""ID"" /><FieldRef Name=""SortOrder"" /><FieldRef Name=""MultipleChoice"" /><FieldRef Name=""Author"" /><FieldRef Name=""Created"" /><FieldRef Name=""Editor"" /><FieldRef Name=""Modified"" />";
                        query.Query = @"<Query><Where><And><IsNotNull><FieldRef Name=""Title"" /></IsNotNull><Eq><FieldRef Name=""ID"" /><Value Type='Counter'>" + pollID.ToString() + "</Value></Eq></And></Where></Query>";

                        SPList objList = objWeb.Lists[SPPollList];
                        SPListItemCollection filteredItems = objList.GetItems(query);

                        foreach (SPListItem item in filteredItems)
                        {
                            if (pollID.Equals(Convert.ToInt32(item["ID"])))
                            {
                                foundPoll.PollID = Convert.ToInt32(item["ID"]);
                                foundPoll.PollTitle = item["Title"].ToString();
                                foundPoll.ExpireOn = DateTime.Parse(item["ExpiresOn"].ToString());
                                foundPoll.SortOrder = item["SortOrder"].ToString();
                                foundPoll.IsActive = item["Active"].ToString();
                                foundPoll.AnonymousVote = item["AnonsCanVote"].ToString();
                                foundPoll.MultiChoice = item["MultipleChoice"].ToString();

                            }
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                //String.Format("{0}: {1}", ErrorMessage.Error, ex.Message);
            }

            return foundPoll;

        }

        /// <summary>
        /// View all polls - active and inactive
        /// </summary>
        /// <returns>List of all polls</returns>
        public List<PollMaster> ViewAllPoll()
        {
            List<PollMaster> foundPollList = new List<PollMaster>();

            try
            {
                using (SPSite objSite = new SPSite(listLocation))
                {
                    using (SPWeb objWeb = objSite.OpenWeb())
                    {
                        SPQuery query = new SPQuery();
                        query.ViewFields = @"<FieldRef Name=""Title"" /><FieldRef Name=""Active"" /><FieldRef Name=""AnonsCanVote"" /><FieldRef Name=""Category"" /><FieldRef Name=""ExpiresOn"" /><FieldRef Name=""ID"" /><FieldRef Name=""SortOrder"" /><FieldRef Name=""MultipleChoice"" /><FieldRef Name=""Author"" /><FieldRef Name=""Created"" /><FieldRef Name=""Editor"" /><FieldRef Name=""Modified"" /><FieldRef Name=""PublishResult"" />";
                        query.Query = @"<Query><OrderBy><FieldRef Name=""ExpiresOn"" Ascending=""False""></FieldRef></OrderBy><Where><IsNotNull><FieldRef Name=""Title"" /></IsNotNull></Where></Query>";

                        SPList objList = objWeb.Lists[SPPollList];
                        SPListItemCollection filteredItems = objList.GetItems(query);

                        foreach (SPListItem item in filteredItems)
                        {
                            if ((String.Compare(item["Active"].ToString(), "No", true) == 0) && (Convert.ToBoolean(item["PublishResult"].ToString())))
                            { 
                                PollMaster foundPoll = new PollMaster();

                                foundPoll.PollID = Convert.ToInt32(item["ID"]);
                                foundPoll.PollTitle = item["Title"].ToString();
                                foundPoll.ExpireOn = DateTime.Parse(item["ExpiresOn"].ToString());
                                foundPoll.SortOrder = item["SortOrder"].ToString();
                                foundPoll.IsActive = item["Active"].ToString();
                                foundPoll.AnonymousVote = item["AnonsCanVote"].ToString();
                                foundPoll.MultiChoice = item["MultipleChoice"].ToString();
                                foundPoll.PublishResult = Convert.ToBoolean(item["PublishResult"].ToString());

                                char[] separator = { '#' };
                                string author = item["Author"].ToString().TrimStart(separator);
                                string editor = item["Editor"].ToString().TrimStart(separator);

                                foundPoll.CreatedBy = author;
                                foundPoll.CreatedDate = DateTime.Parse(item["Created"].ToString());
                                foundPoll.ModifiedBy = editor;
                                foundPoll.ModifiedDate = DateTime.Parse(item["Modified"].ToString());

                                foundPollList.Add(foundPoll);

                            }
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                //String.Format("{0}: {1}", ErrorMessage.Error, ex.Message);
            }

            if (foundPollList.Count != 0)
            {
                DateComparerExpire dc = new DateComparerExpire();
                foundPollList.Sort(dc);
            }
            return foundPollList;

        }
    }
}